<!--
 * @Author: daifen
 * @Date: 2020-06-30 15:44:58
 * @LastEditors: daifen
--> 
<template>
  <div>
    <div style="width:100%;height:100%;" :id="echarts" class="echarts" ref="echarts"></div>
  </div>
</template>

<script>
// 引入echarts
import echarts from "echarts";
export default {
  name: "commonPieChart",
  props: {
    // series中的值
    chartData: {
      type: Array,
      default: () => []
    },
    //标题文字
    title: {
      type: String,
      default: ""
    },
    //副标题文字
    subtext: {
      type: String,
      default: ""
    },
    //legend的数据
    legendShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      legendData: []
    };
  },
  methods: {
    drawChart() {
      const self = this;
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById(this.echarts));
      // 绘制图表
      myChart.setOption({
        title: {
          text: self.title,
          subtext: self.subtext,
          left: "center"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: self.legendData
        },
        series: [
          {
            name: "",
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: self.chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      });
    },
    //处理传过来的json中的值,生成legendData
    handleChartData() {
      const self = this;
      this.chartData.forEach(val => {
        self.legendData.push(val.name);
      });
    }
  },
  computed: {
    echarts() {
      return "echarts" + Math.random() * 100000;
    }
  },
  mounted: function() {
    const self = this;

    if (self.legendShow) {
      this.handleChartData();
    }

    self.$nextTick(() => {
      self.drawChart();
    });
  },
  created: () => {}
};
</script>

<style scoped>
</style>